package com.audio.service.impl;

import com.audio.mapper.UserMapper;
import com.audio.pojo.dto.UserLoginDTO;
import com.audio.pojo.entity.User;
import com.audio.pojo.vo.UserLoginVO;
import com.audio.properties.JwtProperties;
import com.audio.service.UserService;
import com.audio.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;


@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        User user = userMapper.getByUsername(username);
        if (user == null) {
            //账号不存在
            throw new RuntimeException("账号不存在");
        }

        //密码对比
        //进行md5加密再对比
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new RuntimeException("密码错误");
        }

        return getUserLoginVO(user);
    }

    /**
     * 封装的登录和注册的返回方法
     * @param user
     * @return
     */
    private UserLoginVO getUserLoginVO(User user) {
        //生成token
        Map<String, Object> claims = new HashMap<>();
        //存入用户id和role信息
        claims.put("userId", user.getId());
        claims.put("userRole", user.getRole());
        String token = JwtUtil.creatJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        return UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();
    }


}
